import { useState } from "react";
import { Button, Form, Input, App } from "antd";
import type { Login as LoginInterface } from "@/types/api";
import { login } from "@/api";
import storage from "@/utils/storage";
import { useStore } from "@/store";
import styles from "./index.module.scss";
export default function Login() {
    const { message } = App.useApp();
    const [loading, setLoading] = useState(false);
    const state = useStore();
    const onFinish = async (values: LoginInterface.params) => {
        try {
            setLoading(true);
            const data: any = await login(values);
            setLoading(false);
            storage.set("token", data);
            state.updateToken(data);
            message.success("登录成功");
            const params = new URLSearchParams(location.search);
            setTimeout(() => {
                location.href = params.get("callback") || "/welcome";
            });
        } catch (error) {
            setLoading(false);
        }
    };

    const onFinishFailed = (errorInfo: any) => {
        console.log("Failed:", errorInfo);
    };
    return (
        <div className={styles.login}>
            <div className={styles.loginWrapper}>
                <div className={styles.title}>系统登陆</div>
                <Form name="basic" style={{ maxWidth: 600 }} onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete="off">
                    <Form.Item name="userName" rules={[{ required: true, message: "Please input your username!" }]}>
                        <Input />
                    </Form.Item>

                    <Form.Item name="userPwd" rules={[{ required: true, message: "Please input your password!" }]}>
                        <Input.Password />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" loading={loading} htmlType="submit" block>
                            登陆
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
}
